package com.geek.thread.base;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 一个线程获取另一个线程的成员变量
 * 同样涉及到内存屏障的问题，详细参考VolatileTest类
 * @Author Hydra
 * @Date 2022/6/26 10:37
 */
@Slf4j
public class GetOtherVar {

    class ThreadA extends Thread{
        private final ThreadB b;
        public ThreadA(ThreadB b){
            this.b = b;        }
        @Override
        public void run() {
            while (!b.stop){
            }
            log.info("停止线程A");
        }
    }

    class ThreadB extends Thread{
        boolean stop = false;
        @SneakyThrows
        @Override
        public void run() {
            Thread.sleep(1000);
            log.info("关闭变量");
            stop = true;
        }
    }

    void start(){
        ThreadB threadB = new ThreadB();
        ThreadA threadA = new ThreadA(threadB);
        threadA.start();
        threadB.start();
    }

    public static void main(String[] args) {
        GetOtherVar getOtherVar = new GetOtherVar();
        getOtherVar.start();
    }

}
